package com.itheima.media.service.impl;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.util.JwtUtil;
import com.itheima.common.util.Md5Util;
import com.itheima.media.mapper.WmUserMapper;
import com.itheima.media.pojo.WmUser;
import com.itheima.media.service.WmUserService;
import com.mysql.cj.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-20
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;

    /***
     * 登录
     * @param user
     * @return
     */
    @Override
    public String login(WmUser user) {
        //1)根据名字查询wmUser对象
        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<WmUser>();
        queryWrapper.eq("name",user.getName());
        WmUser wmUser = wmUserMapper.selectOne(queryWrapper);

        if(wmUser!=null){
            //2)获取wmUser对象的盐
            String pwd = Md5Util.toMD5(user.getPassword(),wmUser.getSalt());
            //3)MD5(user.password+wmUser.salt)==? wmUser.password
            if(pwd.equals(wmUser.getPassword())){
                //4)如果匹配成功，则颁发令牌
                wmUser.setPassword("*");
                Map<String,Object> dataMap = BeanMap.create(wmUser);
                return JwtUtil.create(dataMap);
            }
            //5)否则返回null
        }
        return null;
    }
}
